package com.example.unique.ui.gallery

import android.annotation.SuppressLint
import android.database.Cursor
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.unique.database.DatabaseJob
import kotlinx.coroutines.*
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

data class Job(
    val id: Int,
    val club: String,
    val startTime: String,
    val endTime: String,
    val target: String,
    val radius: Double,
    val jobStatus: Int,
    val taskName: String
)
class GalleryViewModel(private val jobDatabase: DatabaseJob) : ViewModel() {

    private val _jobList = MutableLiveData<List<Job>>()
    val jobList: LiveData<List<Job>> get() = _jobList
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())

    private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
        Log.e("GalleryViewModel", "协程异常: ${throwable.message}", throwable)
    }

    private val coroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob() + coroutineExceptionHandler)

    //1
    @SuppressLint("Range")
    fun getJobsByClub(club: String) {
        coroutineScope.launch {
            val cursor: Cursor = jobDatabase.getJobsByClub(club)
            val jobs = mutableListOf<Job>()
            if (cursor.moveToFirst()) {
                do {
                    val job = Job(
                        id = cursor.getInt(cursor.getColumnIndex("id")),
                        club = cursor.getString(cursor.getColumnIndex("club")),
                        startTime = cursor.getString(cursor.getColumnIndex("startTime")),
                        endTime = cursor.getString(cursor.getColumnIndex("endTime")),
                        target = cursor.getString(cursor.getColumnIndex("target")),
                        radius = cursor.getDouble(cursor.getColumnIndex("radius")),
                        jobStatus = cursor.getInt(cursor.getColumnIndex("jobStatus")),
                        taskName = cursor.getString(cursor.getColumnIndex("taskName"))
                    )
                    jobs.add(job)
                } while (cursor.moveToNext())
            }
            cursor.close()
            _jobList.postValue(jobs)
        }
    }
    // 获取特定俱乐部和任务状态的任务列表
    @SuppressLint("Range")
    fun getJobsByClubAndStatus(club: String, status: Int) {
        val cursor: Cursor = jobDatabase.getJobsByClubAndStatus(club,status)
        val jobs = mutableListOf<Job>()
        if (cursor.moveToFirst()) {
            do {
                val job = Job(
                    id = cursor.getInt(cursor.getColumnIndex("id")),
                    club = cursor.getString(cursor.getColumnIndex("club")),
                    startTime = cursor.getString(cursor.getColumnIndex("startTime")),
                    endTime = cursor.getString(cursor.getColumnIndex("endTime")),
                    target = cursor.getString(cursor.getColumnIndex("target")),
                    radius = cursor.getDouble(cursor.getColumnIndex("radius")),
                    jobStatus = cursor.getInt(cursor.getColumnIndex("jobStatus")),
                    taskName = cursor.getString(cursor.getColumnIndex("taskName"))
                )
                jobs.add(job)
            } while (cursor.moveToNext())
        }
        cursor.close()
        _jobList.value = jobs
    }

    // 监控任务状态并实时更新
    fun monitorJobStatus(club: String) {
        //1
        coroutineScope.launch {
            while (isActive) {
                val currentTime = System.currentTimeMillis()
                val updatedJobs = mutableListOf<Job>()

                // 检查是否有任务列表
                _jobList.value?.forEach { job ->
                    val startTime = parseDate(job.startTime) ?: return@forEach
                    val endTime = parseDate(job.endTime) ?: return@forEach

                    val newStatus = when {
                        currentTime in startTime until endTime -> 1
                        currentTime >= endTime -> 3
                        else -> 0
                    }

                    if (job.jobStatus != newStatus) {
                        try {
                            jobDatabase.updateStatus(club, job.taskName, newStatus)
                        } catch (e: Exception) {
                            Log.e("GalleryViewModel", "更新任务状态失败: ${e.message}", e)
                        }
                    }

                    updatedJobs.add(job.copy(jobStatus = newStatus))
                }

                _jobList.postValue(updatedJobs.toList())
                delay(10000)
            }
        }

    }

    // 尝试解析日期，如果日期字符串是 "今天"，则返回当前日期的时间
    private fun parseDate(dateString: String): Long? {
        return try {
            if (dateString.contains("今天")) {
                val currentDate = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date())
                val formattedDateString = dateString.replace("今天", currentDate) + ":00"
                dateFormat.parse(formattedDateString)?.time
            } else if (dateString.isNotEmpty()) {
                dateFormat.parse(dateString)?.time
            } else {
                null
            }
        } catch (e: ParseException) {
            Log.e("GalleryViewModel", "日期解析失败: $dateString", e)
            null
        }
    }


    override fun onCleared() {
        super.onCleared()
        coroutineScope.cancel()
    }

}




